package com.sp.scmdb.action.interceptor;

import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.sp.scmdb.bean.UserBean;
import com.sp.scmdb.entity.Menu;
import com.sp.scmdb.utils.GroupList;

public class LoginInterceptor extends MethodFilterInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static org.apache.commons.logging.Log log = LogFactory
			.getLog(LoginInterceptor.class);

	@SuppressWarnings( { "unchecked", "static-access" })
	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		try {
			Map sessionMap = invocation.getInvocationContext().getSession();
			invocation.getInvocationContext().getContext().setLocale(
					Locale.CHINESE);
			HttpServletRequest request = (HttpServletRequest) invocation
					.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
			String menuID = request.getParameter("menuID");
			UserBean user = (UserBean) sessionMap.get("user");
			List<Menu> menus = (List<Menu>) sessionMap.get("menus");
			Map<String, Menu> mapMenu = GroupList.groupMenu(menus);
			if (user != null && MapUtils.isNotEmpty(mapMenu)) {
				if (StringUtils.isNotEmpty(menuID)) {
					Menu menu = mapMenu.get(menuID);
					sessionMap.put("parentMenu", mapMenu.get(menu.getPCd())
							.getCdesc());
					sessionMap.put("currentMenu", menu.getCdesc());
					sessionMap.put("user", user);
				}
				String returnName = invocation.invoke();
				return returnName;
			}
			return "login";
		} catch (Exception e) {
			log.error("session fail!" + e.getMessage());
			return "login";
		}
	}

}
